package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.ObjUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysRegisterService;
import com.ruoyi.manage.enterprise.domain.EcEnterpriseInformation;
import com.ruoyi.manage.enterprise.service.IEcEnterpriseInformationService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 注册验证
 *
 * @author ruoyi
 */
@RestController
public class SysRegisterController extends BaseController {
    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    IEcEnterpriseInformationService iEcEnterpriseInformationService;

    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterBody user) {
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) {
            return error("当前系统没有开启注册功能！");
        }
        String msg = registerService.register(user);
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }

    @Anonymous
    @PostMapping("/registerEnterprise")
    public AjaxResult registerEnterprise(@RequestBody RegisterBody user) {
        SysUser sysUser = iSysUserService.selectUserByPhonenumber(user.getPhonenumber(), 0);


        if (ObjUtil.isNotNull(sysUser)) {
            throw new CustomException("当前手机号已注册，请直接登录");
        }

//        查询企业名称是否存在
        boolean exists = iEcEnterpriseInformationService.lambdaQuery().eq(EcEnterpriseInformation::getEnterpriseName, user.getCompanyName()).exists();
        if (exists) {
            throw new CustomException("企业已注册，请选择其他企业");
        }
//        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser"))))
//        {
//            return error("当前系统没有开启注册功能！");
//        }
        String msg = registerService.registerEnterpriseUser(user);
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }
}
